// pages/challenge/challenge.js
const wordsData = {
  "animals": [
    {"word": "cat", "chinese": "猫", "image": "/images/words/cat.png", "sound": "/sounds/word-cat.mp3"},
    {"word": "dog", "chinese": "狗", "image": "/images/words/dog.png", "sound": "/sounds/word-dog.mp3"},
    {"word": "bird", "chinese": "鸟", "image": "/images/words/bird.png", "sound": "/sounds/word-bird.mp3"},
    {"word": "fish", "chinese": "鱼", "image": "/images/words/fish.png", "sound": "/sounds/word-fish.mp3"},
    {"word": "rabbit", "chinese": "兔子", "image": "/images/words/rabbit.png", "sound": "/sounds/word-rabbit.mp3"},
    {"word": "tiger", "chinese": "老虎", "image": "/images/words/tiger.png", "sound": "/sounds/word-tiger.mp3"},
    {"word": "lion", "chinese": "狮子", "image": "/images/words/lion.png", "sound": "/sounds/word-lion.mp3"},
    {"word": "elephant", "chinese": "大象", "image": "/images/words/elephant.png", "sound": "/sounds/word-elephant.mp3"}
  ],
  "fruits": [
    {"word": "apple", "chinese": "苹果", "image": "/images/words/apple.png", "sound": "/sounds/word-apple.mp3"},
    {"word": "banana", "chinese": "香蕉", "image": "/images/words/banana.png", "sound": "/sounds/word-banana.mp3"},
    {"word": "orange", "chinese": "橙子", "image": "/images/words/orange.png", "sound": "/sounds/word-orange.mp3"},
    {"word": "grape", "chinese": "葡萄", "image": "/images/words/grape.png", "sound": "/sounds/word-grape.mp3"},
    {"word": "strawberry", "chinese": "草莓", "image": "/images/words/strawberry.png", "sound": "/sounds/word-strawberry.mp3"},
    {"word": "watermelon", "chinese": "西瓜", "image": "/images/words/watermelon.png", "sound": "/sounds/word-watermelon.mp3"},
    {"word": "pear", "chinese": "梨", "image": "/images/words/pear.png", "sound": "/sounds/word-pear.mp3"},
    {"word": "peach", "chinese": "桃子", "image": "/images/words/peach.png", "sound": "/sounds/word-peach.mp3"}
  ],
  "colors": [
    {"word": "red", "chinese": "红色", "image": "/images/words/red.png", "sound": "/sounds/word-red.mp3"},
    {"word": "blue", "chinese": "蓝色", "image": "/images/words/blue.png", "sound": "/sounds/word-blue.mp3"},
    {"word": "green", "chinese": "绿色", "image": "/images/words/green.png", "sound": "/sounds/word-green.mp3"},
    {"word": "yellow", "chinese": "黄色", "image": "/images/words/yellow.png", "sound": "/sounds/word-yellow.mp3"},
    {"word": "orange", "chinese": "橙色", "image": "/images/words/orange-color.png", "sound": "/sounds/word-orange.mp3"},
    {"word": "purple", "chinese": "紫色", "image": "/images/words/purple.png", "sound": "/sounds/word-purple.mp3"},
    {"word": "pink", "chinese": "粉色", "image": "/images/words/pink.png", "sound": "/sounds/word-pink.mp3"},
    {"word": "black", "chinese": "黑色", "image": "/images/words/black.png", "sound": "/sounds/word-black.mp3"}
  ],
  "numbers": [
    {"word": "one", "chinese": "一", "number": 1, "image": "/images/words/one.png", "sound": "/sounds/word-one.mp3"},
    {"word": "two", "chinese": "二", "number": 2, "image": "/images/words/two.png", "sound": "/sounds/word-two.mp3"},
    {"word": "three", "chinese": "三", "number": 3, "image": "/images/words/three.png", "sound": "/sounds/word-three.mp3"},
    {"word": "four", "chinese": "四", "number": 4, "image": "/images/words/four.png", "sound": "/sounds/word-four.mp3"},
    {"word": "five", "chinese": "五", "number": 5, "image": "/images/words/five.png", "sound": "/sounds/word-five.mp3"},
    {"word": "six", "chinese": "六", "number": 6, "image": "/images/words/six.png", "sound": "/sounds/word-six.mp3"},
    {"word": "seven", "chinese": "七", "number": 7, "image": "/images/words/seven.png", "sound": "/sounds/word-seven.mp3"},
    {"word": "eight", "chinese": "八", "number": 8, "image": "/images/words/eight.png", "sound": "/sounds/word-eight.mp3"},
    {"word": "nine", "chinese": "九", "number": 9, "image": "/images/words/nine.png", "sound": "/sounds/word-nine.mp3"},
    {"word": "ten", "chinese": "十", "number": 10, "image": "/images/words/ten.png", "sound": "/sounds/word-ten.mp3"}
  ]
};

Page({
  data: {
    currentLevel: 1,
    levelStars: 0,
    progress: 0,
    inGame: false,
    currentQuestionIndex: 0,
    questionList: [], // 题目列表（包含题目类型和单词）
    currentQuestion: null,
    questionType: 'listening', // 'listening' 或 'spelling'
    options: [],
    answerSlots: [],
    availableLetters: [],
    currentSound: '',
    isPlaying: false,
    hasAnswered: false,
    showResult: false,
    resultIcon: '',
    resultText: '',
    correctCount: 0,
    showCompleteModal: false,
    earnedStars: 0,
    audioContext: null
  },

  onLoad() {
    // 加载关卡进度
    this.loadLevelProgress();
    
    // 创建音频上下文
    this.audioContext = wx.createInnerAudioContext();
    this.audioContext.onEnded(() => {
      this.setData({
        isPlaying: false
      });
    });
  },

  onUnload() {
    if (this.audioContext) {
      this.audioContext.destroy();
    }
  },

  onShow() {
    // 每次显示页面时重新加载进度
    this.loadLevelProgress();
  },

  // 加载关卡进度
  loadLevelProgress() {
    const records = wx.getStorageSync('learningRecords') || {};
    const challengeData = wx.getStorageSync('challengeData') || {
      currentLevel: 1,
      levelStars: 0
    };
    
    this.setData({
      currentLevel: challengeData.currentLevel || 1,
      levelStars: challengeData.levelStars || 0,
      progress: ((challengeData.currentLevel - 1) * 10) % 100
    });
  },

  // 开始游戏
  startGame() {
    // 生成题目列表（5道拼写 + 5道听音选词，共10道题）
    const questionList = this.generateQuestionList();
    
    this.setData({
      inGame: true,
      currentQuestionIndex: 0,
      questionList: questionList,
      correctCount: 0,
      hasAnswered: false
    });
    
    // 生成第一题
    this.generateQuestion();
  },

  // 生成题目列表（50%拼写 + 50%听音选词，并打乱顺序）
  generateQuestionList() {
    // 合并所有单词
    const allWords = [];
    Object.keys(wordsData).forEach(category => {
      allWords.push(...wordsData[category]);
    });
    
    // 打乱所有单词
    const shuffledWords = this.shuffleArray([...allWords]);
    
    // 生成5道拼写题
    const spellingQuestions = shuffledWords.slice(0, 5).map(word => ({
      type: 'spelling',
      word: word
    }));
    
    // 生成5道听音选词题
    const listeningQuestions = shuffledWords.slice(5, 10).map(word => ({
      type: 'listening',
      word: word
    }));
    
    // 合并并打乱顺序
    const questionList = [...spellingQuestions, ...listeningQuestions];
    return this.shuffleArray(questionList);
  },

  // 生成题目
  generateQuestion() {
    if (this.data.currentQuestionIndex >= this.data.questionList.length) {
      return;
    }
    
    // 合并所有单词（用于生成干扰项）
    const allWords = [];
    Object.keys(wordsData).forEach(category => {
      allWords.push(...wordsData[category]);
    });
    
    // 从题目列表中获取当前题目
    const questionItem = this.data.questionList[this.data.currentQuestionIndex];
    const correctWord = questionItem.word;
    const questionType = questionItem.type;
    
    if (questionType === 'listening') {
      this.generateListeningQuestion(correctWord, allWords);
    } else {
      this.generateSpellingQuestion(correctWord);
    }
  },

  // 生成听音选词题目
  generateListeningQuestion(correctWord, allWords) {
    // 生成选项
    const wrongOptions = allWords
      .filter(word => word.word !== correctWord.word)
      .slice(0, 3);
    
    // 合并选项并打乱顺序（注意：shuffleArray 返回新数组）
    let options = [correctWord, ...wrongOptions];
    options = this.shuffleArray(options);
    
    // 如果是数字类型的单词，添加 circles 数组
    const optionsWithFlag = options.map(word => {
      const option = {
        ...word,
        isCorrect: word.word === correctWord.word,
        selected: false,
        disabled: false
      };
      
      // 如果是数字类型，添加 circles 数组
      if (word.number !== undefined) {
        option.circles = Array(word.number).fill(0);
      }
      
      return option;
    });

    // 如果是数字类型，为当前题目添加 circles 数组
    let currentQuestion = { ...correctWord };
    if (correctWord.number !== undefined) {
      currentQuestion.circles = Array(correctWord.number).fill(0);
    }

    this.setData({
      questionType: 'listening',
      currentQuestion: currentQuestion,
      options: optionsWithFlag,
      currentSound: correctWord.sound,
      hasAnswered: false,
      showResult: false
    });
  },

  // 生成拼写题目
  generateSpellingQuestion(correctWord) {
    const wordLetters = correctWord.word.split('');
    
    // 创建答案槽位（确保每个槽位都是对象）
    const answerSlots = wordLetters.map(() => ({ letter: '' }));
    
    // 将单词的字母拆分成独立的字母，并打乱顺序（不添加干扰字母）
    let availableLetters = wordLetters.map(letter => ({
      letter: letter.toUpperCase(),
      used: false
    }));
    
    // 打乱字母顺序（注意：shuffleArray 返回新数组）
    availableLetters = this.shuffleArray(availableLetters);

    // 如果是数字类型，为当前题目添加 circles 数组
    let currentQuestion = { ...correctWord };
    if (correctWord.number !== undefined) {
      currentQuestion.circles = Array(correctWord.number).fill(0);
    }

    this.setData({
      questionType: 'spelling',
      currentQuestion: currentQuestion,
      answerSlots: answerSlots,
      availableLetters: availableLetters,
      hasAnswered: false,
      showResult: false
    });
  },

  // 打乱数组
  shuffleArray(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  // 播放发音（听音选词）
  playSound() {
    if (this.data.hasAnswered || this.data.questionType !== 'listening') return;
    
    if (this.audioContext) {
      this.audioContext.src = this.data.currentSound;
      this.audioContext.play();
      this.setData({
        isPlaying: true
      });
    }
  },

  // 选择选项（听音选词）
  selectOption(e) {
    if (this.data.hasAnswered || this.data.questionType !== 'listening') return;
    
    const index = e.currentTarget.dataset.index;
    const options = [...this.data.options];
    const selectedOption = options[index];
    
    options.forEach((opt, i) => {
      opt.selected = i === index;
      opt.disabled = true;
    });
    
    const isCorrect = selectedOption.isCorrect;
    this.checkAnswer(isCorrect);
    
    this.setData({
      options,
      hasAnswered: true,
      showResult: true,
      resultIcon: isCorrect ? '✅' : '❌',
      resultText: isCorrect ? '答对了！' : '答错了！'
    });
  },

  // 选择字母（拼写）
  selectLetter(e) {
    if (this.data.hasAnswered || this.data.questionType !== 'spelling') return;
    
    const index = parseInt(e.currentTarget.dataset.index);
    const letter = this.data.availableLetters[index];
    
    // 如果字母不存在或已被使用，则忽略
    if (!letter || letter.used) return;
    
    // 找到第一个空槽位
    const emptyIndex = this.data.answerSlots.findIndex(slot => !slot.letter || slot.letter === '');
    if (emptyIndex !== -1) {
      this.placeLetterInSlot(index, emptyIndex);
    }
  },
  
  // 将字母放入槽位
  placeLetterInSlot(letterIndex, slotIndex) {
    const letter = this.data.availableLetters[letterIndex];
    if (!letter || letter.used) return;
    
    // 创建新的答案槽位数组（深拷贝）
    const answerSlots = this.data.answerSlots.map((slot, idx) => {
      if (idx === slotIndex) {
        return { letter: letter.letter };
      }
      return { letter: slot.letter || '' };
    });
    
    // 创建新的可用字母数组（深拷贝）
    const availableLetters = this.data.availableLetters.map((l, idx) => {
      if (idx === letterIndex) {
        return { letter: l.letter, used: true };
      }
      return { letter: l.letter, used: l.used || false };
    });
    
    const isComplete = answerSlots.every(slot => slot.letter && slot.letter !== '');
    
    this.setData({
      answerSlots: answerSlots,
      availableLetters: availableLetters
    });
    
    // 如果填满了，自动检查答案（延迟一下让用户看到效果）
    if (isComplete) {
      setTimeout(() => {
        const userAnswer = answerSlots.map(slot => slot.letter).join('').toLowerCase();
        const correctAnswer = this.data.currentQuestion.word.toLowerCase();
        const isCorrect = userAnswer === correctAnswer;
        
        this.checkAnswer(isCorrect);
        
        this.setData({
          hasAnswered: true,
          showResult: true,
          resultIcon: isCorrect ? '✅' : '❌',
          resultText: isCorrect ? '答对了！' : '答错了！'
        });
      }, 500);
    }
  },

  // 移除字母（拼写）
  removeLetter(e) {
    if (this.data.hasAnswered || this.data.questionType !== 'spelling') return;
    
    const slotIndex = parseInt(e.currentTarget.dataset.index);
    const slot = this.data.answerSlots[slotIndex];
    
    if (!slot || !slot.letter) return;
    
    // 找到对应的字母并恢复
    const letterIndex = this.data.availableLetters.findIndex(
      (l, i) => l.letter === slot.letter && l.used
    );
    
    if (letterIndex !== -1) {
      // 创建新的答案槽位数组（深拷贝）
      const answerSlots = this.data.answerSlots.map((s, idx) => {
        if (idx === slotIndex) {
          return { letter: '' };
        }
        return { letter: s.letter || '' };
      });
      
      // 创建新的可用字母数组（深拷贝）
      const availableLetters = this.data.availableLetters.map((l, idx) => {
        if (idx === letterIndex) {
          return { letter: l.letter, used: false };
        }
        return { letter: l.letter, used: l.used || false };
      });
      
      this.setData({
        answerSlots: answerSlots,
        availableLetters: availableLetters,
        showResult: false
      });
    }
  },

  // 检查答案
  checkAnswer(isCorrect) {
    if (isCorrect) {
      const correctCount = this.data.correctCount + 1;
      this.setData({
        correctCount
      });
    }
    
    // 更新记录
    const app = getApp();
    app.updateRecords('challenge', isCorrect);
  },

  // 下一题
  nextQuestion() {
    if (this.data.currentQuestionIndex >= 9) {
      this.finishLevel();
      return;
    }
    
    const nextIndex = this.data.currentQuestionIndex + 1;
    this.setData({
      currentQuestionIndex: nextIndex,
      hasAnswered: false,
      showResult: false
    });
    
    // 生成下一题
    this.generateQuestion();
  },

  // 完成关卡
  finishLevel() {
    const correctCount = this.data.correctCount;
    const earnedStars = correctCount >= 8 ? 3 : (correctCount >= 6 ? 2 : (correctCount >= 4 ? 1 : 0));
    
    // 保存进度
    const challengeData = {
      currentLevel: this.data.currentLevel + 1,
      levelStars: earnedStars
    };
    wx.setStorageSync('challengeData', challengeData);
    
    this.setData({
      showCompleteModal: true,
      earnedStars,
      inGame: false
    });
  },

  // 处理关卡完成
  handleLevelComplete() {
    this.setData({
      showCompleteModal: false
    });
    
    // 重新加载进度
    this.loadLevelProgress();
  },

  onAudioEnd() {
    this.setData({
      isPlaying: false
    });
  }
});

